//
//  UserBindingPhoneViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/8/8.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "UserBindingPhoneViewController.h"

@interface UserBindingPhoneViewController ()<UITextFieldDelegate>{
    UITextField *txtTel;
    UITextField *txtCode;
    UIButton *btnCode;
    BOOL boolBack;
    UIButton *subBtn;
    
    BOOL boolunbind;
    NSString *stroldmobile;
}

@end

@implementation UserBindingPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIView *viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, 10+kTopHeight, kScreenWidth, 44)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:viewBG];
    
    txtTel =[RHMethods textFieldlWithFrame:CGRectMake(10, 0, kScreenWidth-20, 44) font:fontTitle color:rgbTitleColor placeholder:@"请输入原手机号" text:@""];
    [viewBG addSubview:txtTel];
    
    float temp_y=YH(viewBG)+10;
    viewBG=[[UIView alloc] initWithFrame:CGRectMake(0, temp_y, kScreenWidth, 44)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:viewBG];
    txtCode=[RHMethods textFieldlWithFrame:CGRectMake(10, 0, W(viewBG)-110, 44) font:fontTitle color:rgbTitleColor placeholder:@"请输入验证码" text:@""];
    [viewBG addSubview:txtCode];
    
    btnCode =[RHMethods buttonWithFrame:CGRectMake(XW(txtCode), 0, 100, 44) title:@"获取验证码" image:nil bgimage:nil];
    [btnCode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnCode setBackgroundColor:rgbpublicColor];
    [btnCode addTarget:self action:@selector(codeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [viewBG addSubview:btnCode];
    
    [viewBG addLineLayerWhitframe:CGRectMake(0, 0, W(viewBG), 0.5) whitColor:rgbLineColor];
    [viewBG addLineLayerWhitframe:CGRectMake(0, 43.5, W(viewBG), 0.5) whitColor:rgbLineColor];
    temp_y+=H(viewBG)+10;
   
    txtCode.delegate=self;
    txtTel.delegate=self;
    temp_y+=10;
    subBtn=[RHMethods buttonWithFrame:CGRectMake(10, temp_y,kScreenWidth-20, 40) title:@"下一步" image:@"" bgimage:@"LoginbtnBG"];
    subBtn.titleLabel.font=Font(20);
    [subBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [subBtn addTarget:self action:@selector(submintButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:subBtn];

    
}

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark button
-(void)codeButtonClicked{
    NSString *strTel=txtTel.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"哎呀！手机号是不是没输入啊"];
        return;
    }
    [self loadSendCode:@""];
    
}

-(void)backButtonClicked:(id)sender{
    if (boolBack) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"验证码短信可能略有延迟，确定返回并重新开始？" delegate:self cancelButtonTitle:@"等待" otherButtonTitles:@"返回", nil];
        [alert show];
    }else{
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [super backButtonClicked:sender];
    }
}
-(void)submintButtonClicked{
    [self.view endEditing:YES];
    DLog(@"确定");//ZKpubseditpass
    NSString *strTel=txtTel.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"哎呀！手机号是不是没输入啊"];
        return;
    }
    NSString *strCode=txtCode.text;
    if (![strCode notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"哎呀！验证码是不是没输入啊"];
        return;
    }
    
    krequestParam
    [dictparam setValue:strCode forKey:@"code"];
    NSString *strurl=XKFV4welcomeunbind;
    if (boolunbind) {
        strurl=XKFV4welcomechange;
        [dictparam setValue:strTel forKey:@"newmobile"];
        [dictparam setValue:stroldmobile forKey:@"oldmobile"];
    }else{
        [dictparam setValue:strTel forKey:@"mobile"];
    }
    [NetEngine createPostAction:strurl withParams:dictparam onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            if (boolunbind) {
                [NSObject cancelPreviousPerformRequestsWithTarget:self];
                [[Utility Share] setUserAccount:strTel];
                [[Utility Share] saveUserInfoToDefault];
                [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [super backButtonClicked:nil];
                });
            }else{
                stroldmobile=strTel;
                boolunbind=YES;
                [subBtn setTitle:@"确认绑定" forState:UIControlStateNormal];
                txtTel.text=@"";
                txtTel.placeholder=@"请输入新手机号";
                txtCode.text=@"";
                boolBack=NO;
                [self yanZM_date];
            }
            
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
    
}

-(void)loadSendCode:(NSString *)strCid{
    NSString *strTel=txtTel.text;
   
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    [dict setValue:strTel forKey:@"mobile"];
    [dict setValue:[[Utility Share] userId] forKey:@"uid"];
    [dict setValue:[[Utility Share] userToken] forKey:@"token"];
    
    NSString *strurl=XKFV4welcomeunbindcode;
    if (boolunbind) {
        strurl=XKFV4welcomechangecode;
    }
    
    [NetEngine createHttpActionFixed:strurl withCache:NO withParams:dict withMask:SVProgressHUDMaskTypeNone onCompletion:^(id resData, BOOL isCache) {
        DLog(@"__resData____%@",resData);
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            boolBack=YES;
            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
    
            [btnCode setBackgroundColor:RGBACOLOR(150, 150, 150, 1)];
            btnCode.userInteractionEnabled=NO;
//            [self performSelector:@selector(updateButtonTitle:) withObject:@"60" afterDelay:0];
            [self performSelector:@selector(updateButtonTitle:) withObject:[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"codetime"] afterDelay:0];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    } onError:^(NSError *error) {
        [SVProgressHUD showImage:nil status:alertErrorTxt];
    }];

}

-(void)updateButtonTitle:(NSString *)str{
    float aflote=[str floatValue];
    DLog(@"________________()()()()()(");
    [btnCode setTitle:[NSString stringWithFormat:@"%.0f秒",aflote] forState:UIControlStateNormal];
    if (aflote<=1) {
        [self performSelector:@selector(yanZM_date) withObject:nil afterDelay:1.0];
    }else{
        aflote--;
        [self performSelector:@selector(updateButtonTitle:) withObject:[NSString stringWithFormat:@"%f",aflote] afterDelay:1.0];
    }
}

-(void)yanZM_date{
    DLog(@"延迟——————禁止验证码按钮");
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [btnCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    [btnCode setBackgroundColor:rgbpublicColor];
    btnCode.userInteractionEnabled=YES;
}
#pragma mark UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        boolBack=NO;
        [super backButtonClicked:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
